var express = require("express");
var router = express.Router();
var essayModel = require("../db/jjx");
var multer = require("multer");
var path = require("path");
var fs = require("fs");

/* GET essay listing - 获取所有essay数据 */
router.get("/getessay", async function (req, res, next) {
  try {
    // 获取所有essay数据，按创建时间倒序排列
    const essays = await essayModel.find().sort({ createdata: -1 }); // 按创建时间倒序

    res.json({
      success: true,
      message: "获取essay数据成功",
      data: essays,
      total: essays.length,
    });
  } catch (error) {
    console.error("获取essay数据失败:", error);
    res.status(500).json({
      success: false,
      message: "获取essay数据失败",
      error: error.message,
    });
  }
});

/* GET essay by ID - 根据ID获取单个essay详情 */
router.get("/getessay/:id", async function (req, res, next) {
  try {
    const { id } = req.params;
    const essay = await essayModel.findById(id);

    if (!essay) {
      return res.status(404).json({
        success: false,
        message: "未找到该essay",
      });
    }

    // 增加浏览次数
    essay.views += 1;
    await essay.save();

    res.json({
      success: true,
      message: "获取essay详情成功",
      data: essay,
    });
  } catch (error) {
    console.error("获取essay详情失败:", error);
    res.status(500).json({
      success: false,
      message: "获取essay详情失败",
      error: error.message,
    });
  }
});

/* GET essays with pagination - 分页获取essay列表（用于动态页面渲染） */
router.get("/getessays", async function (req, res, next) {
  try {
    const {
      page = 1,
      limit = 10,
      topic,
      tag,
      author,
      sort = "latest",
      startDate,
      endDate,
    } = req.query;
    const skip = (page - 1) * limit;

    // 构建查询条件
    let query = {};
    if (topic) {
      query.topic = { $in: [topic] };
    }
    if (tag) {
      query.tag = { $in: [tag] };
    }
    if (author) {
      query["author.name"] = new RegExp(author, "i");
    }

    // 添加日期范围查询
    if (startDate || endDate) {
      query.createdata = {};
      if (startDate) {
        const startDateTime = new Date(startDate);
        query.createdata.$gte = startDateTime;
        console.log("开始日期:", startDate, "解析后:", startDateTime);
      }
      if (endDate) {
        const endDateTime = new Date(endDate);
        query.createdata.$lt = endDateTime;
        console.log("结束日期:", endDate, "解析后:", endDateTime);
      }
      console.log("日期查询条件:", query.createdata);
    }

    // 根据排序参数决定排序方式
    let sortOption = {};
    if (sort === "hot") {
      // 热门排序：主要按阅读量（浏览量）排序，其次按点赞数排序
      // 注意：MongoDB不能直接按数组长度排序，需要在前端处理
      sortOption = {
        views: -1, // 浏览量降序（主要排序）
        createdata: -1, // 创建时间降序（次要排序）
      };
    } else {
      // 最新排序：按创建时间排序
      sortOption = { createdata: -1 };
    }

    console.log("最终查询条件:", JSON.stringify(query, null, 2));

    const essays = await essayModel
      .find(query)
      .sort(sortOption)
      .skip(skip)
      .limit(parseInt(limit));

    const total = await essayModel.countDocuments(query);

    console.log(`查询结果: 找到 ${total} 条记录, 返回 ${essays.length} 条`);
    if (essays.length > 0) {
      console.log("第一条数据的创建时间:", essays[0].createdata);
    }

    res.json({
      success: true,
      message: "获取essay列表成功",
      data: essays,
      pagination: {
        current: parseInt(page),
        pageSize: parseInt(limit),
        total,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error("获取essay列表失败:", error);
    res.status(500).json({
      success: false,
      message: "获取essay列表失败",
      error: error.message,
    });
  }
});

/* GET categories - 获取所有分类标签 */
router.get("/categories", async function (req, res, next) {
  try {
    // 从essay数据中提取所有唯一的topic和tag
    const essays = await essayModel.find({}, { topic: 1, tag: 1 });

    const allTopics = new Set();
    const allTags = new Set();

    essays.forEach((essay) => {
      if (essay.topic) {
        essay.topic.forEach((topic) => allTopics.add(topic));
      }
      if (essay.tag) {
        essay.tag.forEach((tag) => allTags.add(tag));
      }
    });

    res.json({
      success: true,
      message: "获取分类成功",
      data: {
        topics: Array.from(allTopics),
        tags: Array.from(allTags),
      },
    });
  } catch (error) {
    console.error("获取分类失败:", error);
    res.status(500).json({
      success: false,
      message: "获取分类失败",
      error: error.message,
    });
  }
});

/* GET search essays - 搜索essay */
router.get("/search", async function (req, res, next) {
  try {
    const { keyword, page = 1, limit = 20, topic, tag } = req.query;

    if (!keyword) {
      return res.status(400).json({
        success: false,
        message: "搜索关键词不能为空",
      });
    }

    const skip = (page - 1) * limit;

    // 构建搜索查询条件
    let query = {
      $or: [
        { context: { $regex: keyword, $options: "i" } }, // 搜索内容，忽略大小写
        { topic: { $in: [new RegExp(keyword, "i")] } }, // 搜索话题
        { tag: { $in: [new RegExp(keyword, "i")] } }, // 搜索标签
      ],
    };

    // 如果指定了话题，添加话题过滤
    if (topic) {
      query.topic = { $in: [topic] };
    }

    // 如果指定了标签，添加标签过滤
    if (tag) {
      query.tag = { $in: [tag] };
    }

    console.log("搜索查询条件:", JSON.stringify(query, null, 2));

    // 执行搜索，按照相关性和时间排序
    const essays = await essayModel
      .find(query)
      .sort({
        createdata: -1, // 按时间倒序
        views: -1, // 按浏览量倒序
      })
      .skip(skip)
      .limit(parseInt(limit));

    const total = await essayModel.countDocuments(query);

    console.log(`搜索关键词 "${keyword}" 找到 ${total} 条结果`);

    res.json({
      success: true,
      message: "搜索成功",
      data: essays,
      pagination: {
        current: parseInt(page),
        pageSize: parseInt(limit),
        total,
        totalPages: Math.ceil(total / limit),
      },
      searchInfo: {
        keyword,
        resultCount: total,
      },
    });
  } catch (error) {
    console.error("搜索失败:", error);
    res.status(500).json({
      success: false,
      message: "搜索失败",
      error: error.message,
    });
  }
});

/* POST create essay - 创建新的动态/essay */
router.post("/createessay", async function (req, res, next) {
  try {
    const {
      context,
      img = [],
      topic = [],
      anonymity = false,
      tag = [],
      author,
      isTop = false, // 是否置顶
    } = req.body;

    // 增强数据验证
    if (
      !context ||
      typeof context !== "string" ||
      context.trim().length === 0
    ) {
      return res.status(400).json({
        success: false,
        message: "动态内容不能为空",
      });
    }

    if (!author || !author._id || !author.name) {
      return res.status(400).json({
        success: false,
        message: "作者信息不完整",
      });
    }

    // 验证内容长度限制
    if (context.length > 500) {
      return res.status(400).json({
        success: false,
        message: "动态内容不能超过500字符",
      });
    }

    // 验证图片数量限制
    if (img.length > 9) {
      return res.status(400).json({
        success: false,
        message: "最多只能上传9张图片",
      });
    }

    // 验证话题数量限制
    if (topic.length > 3) {
      return res.status(400).json({
        success: false,
        message: "最多只能选择3个话题",
      });
    }

    // 处理置顶时间
    let topTime = "999"; // 默认不置顶
    if (isTop) {
      // 置顶时间设置为当前时间戳
      topTime = new Date().getTime().toString();
    }

    // 创建新的动态
    const newEssay = new essayModel({
      context: context.trim(),
      img: Array.isArray(img) ? img : [],
      topic: Array.isArray(topic) ? topic : [],
      anonymity: Boolean(anonymity),
      tag: Array.isArray(tag) ? tag : [],
      author: {
        _id: author._id,
        name: author.name,
        avatar: author.avatar || "",
      },
      top_time: topTime,
      createdata: new Date(),
      views: 0,
      comments: 0,
      likes: [],
    });

    // 保存到数据库
    const savedEssay = await newEssay.save();

    console.log("动态创建成功:", {
      id: savedEssay._id,
      author: savedEssay.author.name,
      content: savedEssay.context.substring(0, 50) + "...",
      isAnonymous: savedEssay.anonymity,
      isTop: isTop,
    });

    res.json({
      success: true,
      message: "发布动态成功",
      data: {
        _id: savedEssay._id,
        context: savedEssay.context,
        img: savedEssay.img,
        topic: savedEssay.topic,
        anonymity: savedEssay.anonymity,
        tag: savedEssay.tag,
        author: savedEssay.author,
        top_time: savedEssay.top_time,
        createdata: savedEssay.createdata,
        views: savedEssay.views,
        comments: savedEssay.comments,
        likes: savedEssay.likes,
      },
    });
  } catch (error) {
    console.error("创建动态失败:", error);

    // 根据错误类型返回不同的错误信息
    let errorMessage = "发布动态失败";
    if (error.name === "ValidationError") {
      errorMessage = "数据格式不正确";
    } else if (error.name === "CastError") {
      errorMessage = "数据类型错误";
    }

    res.status(500).json({
      success: false,
      message: errorMessage,
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
});

/* POST like essay - 点赞essay */
router.post("/likeessay/:id", async function (req, res, next) {
  try {
    const { id } = req.params;
    const { userId } = req.body;

    if (!userId) {
      return res.status(400).json({
        success: false,
        message: "用户ID不能为空",
      });
    }

    const essay = await essayModel.findById(id);
    if (!essay) {
      return res.status(404).json({
        success: false,
        message: "未找到该essay",
      });
    }

    // 检查用户是否已经点赞
    const alreadyLiked = essay.likes.includes(userId);

    if (alreadyLiked) {
      // 取消点赞
      essay.likes = essay.likes.filter(
        (likeId) => likeId.toString() !== userId
      );
    } else {
      // 添加点赞
      essay.likes.push(userId);
    }

    await essay.save();

    res.json({
      success: true,
      message: alreadyLiked ? "取消点赞成功" : "点赞成功",
      data: {
        likes: essay.likes.length,
        isLiked: !alreadyLiked,
      },
    });
  } catch (error) {
    console.error("点赞操作失败:", error);
    res.status(500).json({
      success: false,
      message: "点赞操作失败",
      error: error.message,
    });
  }
});

// 配置multer用于文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // 确保上传目录存在
    const uploadDir = path.join(__dirname, "../public/uploads/images");
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名：时间戳 + 随机数 + 原扩展名
    const ext = path.extname(file.originalname);
    const filename = Date.now() + "-" + Math.round(Math.random() * 1e9) + ext;
    cb(null, filename);
  },
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 检查文件类型
  if (file.mimetype.startsWith("image/")) {
    cb(null, true);
  } else if (file.mimetype.startsWith("video/")) {
    cb(null, true);
  } else {
    cb(new Error("只支持图片和视频文件"), false);
  }
};

const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 50 * 1024 * 1024, // 50MB限制，适合视频文件
    files: 9, // 最多9个文件
  },
});

/* POST upload media files - 上传图片/视频文件 */
router.post("/upload", (req, res, next) => {
  // 确保上传目录存在
  const uploadDir = path.join(__dirname, "../public/uploads/images");
  if (!fs.existsSync(uploadDir)) {
    try {
      fs.mkdirSync(uploadDir, { recursive: true });
      console.log("创建上传目录:", uploadDir);
    } catch (error) {
      console.error("创建上传目录失败:", error);
      return res.status(500).json({
        success: false,
        message: "服务器配置错误：无法创建上传目录",
        error: error.message,
      });
    }
  }

  // 使用multer处理文件上传
  upload.array("files", 9)(req, res, function (err) {
    if (err) {
      console.error("Multer错误:", err);

      let errorMessage = "文件上传失败";
      if (err.code === "LIMIT_FILE_SIZE") {
        errorMessage = "文件大小超过50MB限制";
      } else if (err.code === "LIMIT_FILE_COUNT") {
        errorMessage = "文件数量超过9个限制";
      } else if (err.message === "只支持图片和视频文件") {
        errorMessage = err.message;
      }

      return res.status(400).json({
        success: false,
        message: errorMessage,
        error: err.message,
      });
    }

    try {
      if (!req.files || req.files.length === 0) {
        return res.status(400).json({
          success: false,
          message: "没有上传任何文件",
        });
      }

      // 处理上传的文件
      const uploadedFiles = req.files.map((file) => {
        const fileUrl = `/uploads/images/${file.filename}`;
        const isVideo = file.mimetype.startsWith("video/");

        return {
          filename: file.filename,
          originalname: file.originalname,
          mimetype: file.mimetype,
          size: file.size,
          url: fileUrl,
          type: isVideo ? "video" : "image",
          // 如果是视频，添加一些默认信息（实际项目中可以使用 ffmpeg 等工具获取真实信息）
          duration: isVideo ? Math.floor(Math.random() * 60) + 10 : undefined, // 模拟10-70秒的视频时长
          poster: isVideo ? fileUrl + "?poster=true" : undefined, // 模拟视频封面
        };
      });

      console.log("文件上传成功:", {
        count: uploadedFiles.length,
        files: uploadedFiles.map((f) => ({
          name: f.originalname,
          size: f.size,
          type: f.type,
        })),
      });

      res.json({
        success: true,
        message: "文件上传成功",
        data: {
          files: uploadedFiles,
          count: uploadedFiles.length,
        },
      });
    } catch (error) {
      console.error("文件处理失败:", error);

      // 清理可能已上传的文件
      if (req.files) {
        req.files.forEach((file) => {
          try {
            fs.unlinkSync(file.path);
          } catch (unlinkError) {
            console.error("清理文件失败:", unlinkError);
          }
        });
      }

      let errorMessage = "文件上传失败";
      if (error.code === "LIMIT_FILE_SIZE") {
        errorMessage = "文件大小超过50MB限制";
      } else if (error.code === "LIMIT_FILE_COUNT") {
        errorMessage = "文件数量超过9个限制";
      } else if (error.message === "只支持图片和视频文件") {
        errorMessage = error.message;
      }

      res.status(500).json({
        success: false,
        message: errorMessage,
        error:
          process.env.NODE_ENV === "development" ? error.message : undefined,
      });
    }
  });
});

/* DELETE delete media file - 删除上传的文件 */
router.delete("/upload/:filename", async function (req, res, next) {
  try {
    const { filename } = req.params;

    if (!filename) {
      return res.status(400).json({
        success: false,
        message: "文件名不能为空",
      });
    }

    const filePath = path.join(__dirname, "../public/uploads/images", filename);

    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({
        success: false,
        message: "文件不存在",
      });
    }

    // 删除文件
    fs.unlinkSync(filePath);

    console.log("文件删除成功:", filename);

    res.json({
      success: true,
      message: "文件删除成功",
    });
  } catch (error) {
    console.error("文件删除失败:", error);
    res.status(500).json({
      success: false,
      message: "文件删除失败",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
});

/* GET get media file - 获取媒体文件 */
router.get("/media/:filename", function (req, res, next) {
  try {
    const { filename } = req.params;
    const filePath = path.join(__dirname, "../public/uploads/images", filename);

    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({
        success: false,
        message: "文件不存在",
      });
    }

    // 设置适当的Content-Type
    const ext = path.extname(filename).toLowerCase();
    let contentType = "application/octet-stream";

    if ([".jpg", ".jpeg", ".png", ".gif", ".webp"].includes(ext)) {
      contentType = `image/${ext.substring(1)}`;
    } else if ([".mp4", ".webm", ".ogg"].includes(ext)) {
      contentType = `video/${ext.substring(1)}`;
    }

    res.setHeader("Content-Type", contentType);
    res.sendFile(filePath);
  } catch (error) {
    console.error("获取文件失败:", error);
    res.status(500).json({
      success: false,
      message: "获取文件失败",
    });
  }
});

module.exports = router;
